package index;

import java.util.Map;
import java.util.HashMap;
import java.io.*;

public class InvertedIndex {
	private Map<String, Map<Integer, Integer>> index = new HashMap<String, Map<Integer, Integer>>();
	private Map<Integer, Integer> subIndex; 

	public void createIndex(String filePath) {
		try {
			File file = new File(filePath);
			InputStream is = new FileInputStream(file);
			BufferedReader read = new BufferedReader(new InputStreamReader(is));
			String temp = null;
			int line = 1;
			while ((temp = read.readLine()) != null) {
				String[] words = temp.split(" ");
				for (String word : words) {
					if (!index.containsKey(word)) {//新索引
						subIndex = new HashMap<Integer, Integer>();
						subIndex.put(line, 1);
						index.put(word, subIndex);
					}else {
						subIndex = index.get(word);//已索引过
						if (subIndex.containsKey(line)) {
							int count = subIndex.get(line);
							subIndex.put(line, count + 1);
						} else {
							subIndex.put(line, 1);
						}
					}
				}
				line++;
			}
			read.close();
			is.close();
		} catch (IOException e) {
			System.out.println(e);
		}
	}

	public void find(String str) {
		String[] words = str.split(" ");
		for (String word : words) {
			StringBuilder sb = new StringBuilder();
			if (index.containsKey(word)) {
				sb.append("word: " + word + " in ");
				Map<Integer, Integer> temp = index.get(word);
				for (Map.Entry<Integer, Integer> e : temp.entrySet()) {
					sb.append("line " + e.getKey() + " [" + e.getValue()
							+ "] , ");
				}
			} else {
				sb.append("word: " + word + " not found");
			}
			System.out.println(sb);
		}
	}

	public static void main(String[] args) {
		InvertedIndex index = new InvertedIndex();
		index.createIndex("/Users/mengxin/news.txt");
		index.find("I love Shanghai today");
	}
}
